<template>
	<view class="login">
		<button class="showButton" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
			手机号授权登录
		</button>
		<view class="res">
			{{err}}
		</view>
	</view>
</template>

<script>
	import WXBizDataCrypt from "@/common/WXBizDataCrypt.js";
	import {
		getWechatInfo,
		login
	} from "@/api/index.js"
	export default {
		data() {
			return {
				openid: "",
				encryptedData: "",
				iv: "",
				code:"",
				phone: "",
				appid: 'wxb209417f272ce980', //你的小程序的APPID
				session_key: "",
				err: ''
			};
		},
		created() {
			// let _this = this;
			uni.login({
				success: (res) => {
					console.log("res: ", res);
					if (res.code) {
						console.log("res.code: ", res.code);
						this.code = res.code;
						this.getSessionKey()
					}
				},
			});
		},
		methods: {
			getSessionKey() {
				getWechatInfo(this.code).then(res => {
					console.log(res, 'res???????????????');
					this.openid = res.data.openid;
					// console.log("this.openid:获取信息 ", this.openid);
					this.session_key = res.data.session_key;
					// console.log(" this.session_key:获取信息 ", this.session_key);
				})
			},
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.iv = e.detail.iv;
					this.encryptedData = e.detail.encryptedData;
					this.decryptPhone(); //解密手机号函数
				} else {
					wx.showModal({
						title: "提示",
						showCancel: false,
						content: "未授权",
						success: function(res) {
							console.log("res: ", res);
						},
					});
				}
			},
			decryptPhone() {
				let pc = new WXBizDataCrypt(this.appid, this.session_key);
				let data = pc.decryptData(this.encryptedData, this.iv);
				if (data.phoneNumber) {
					this.getRole(data.phoneNumber);
				}
			},
			getRole(phoneNumber) {
				const data = {
					phone: phoneNumber,
				};
				login(data).then((res) => {
						console.log("res:----角色信息 ", res);
						if (res.statusCode == 200) {
							// 执行跳转
							this.phone = phoneNumber;
							uni.setStorageSync('mini-userinfo', res.data.data.user)
							uni.redirectTo({
								url: '/pages/mine/settings/editInfo'
							})
						}
					})
					.catch((err) => {});
			},
		}
	}
</script>

<style lang="scss">
	.login {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 0 60rpx;
		background: #FAF6ED;

		.res {
			width: 100%;
			word-break: break-all;
		}
	}

	.title {
		font-size: 60rpx;
		font-weight: bold;
		color: #000000;
		margin-bottom: 80rpx;
		font-family: Bitstream Vera Serif Bold;
	}

	.showButton {
		width: 100%;
		background: limegreen;
		border-radius: 100rpx;
		color: #ffffff;
	}
</style>